#pragma once

#include "Socket.hpp"
#include "Channel.hpp"
#include "EventLoop.hpp"

class Acceptor
{
private:
    Socket _socket; // 监听套接字
    EventLoop *_loop;
    std::unique_ptr<Channel> _sockfd_channel;

    using AcceptCallback = std::function<void()>;
    AcceptCallback _accept_callback;

private:
    // 读事件就绪回调函数
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if(newfd < 0)
            return;
        if(_accept_callback) 
            _accept_callback();
    }
    // 创建一个服务端通信套接字
    int CreateServer(uint16_t port)
    {
        bool ret = _socket.CreateServer(port);
        assert(ret == true);
        return _socket.Fd();
    }

public:
    Acceptor(EventLoop *loop, uint16_t port)
        : _socket(CreateServer(port)), _loop(loop), _sockfd_channel(new Channel(loop, _socket.Fd()))
    {
        // 设置读回调函数
        _sockfd_channel->SetReadCallBack(std::bind(&Acceptor::HandleRead, this));
    }
    // 设置获取新连接后的回调函数
    void SetAcceptCallback(const AcceptCallback &cb) { _accept_callback = cb; }
    // 启动服务端监听套接字
    void ServerListen() { _sockfd_channel->EnableRead(); }
};